package com.panda.admin.interfaces.file.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.panda.admin.base.FileEntity;
import com.panda.admin.interfaces.file.constant.StorageBucket;
import com.panda.admin.interfaces.file.service.SystemFileService;
import com.panda.admin.login.dto.FileDeleteDto;
import com.panda.admin.login.dto.FileDto;
import com.panda.admin.login.entity.SystemFile;
import com.panda.admin.result.Result;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * author: tcy
 * createDate: 2022/12/28
 * description:文件服务控制层
 */
@Api(tags = "文件服务")
@RestController
@RequestMapping("/file")
public class FileController {


    @Resource
    private StorageBucket storageBucket;

    @Autowired
    private SystemFileService systemFileService;

    /**
     * cos客户端
     */
    public COSClient cosClient(){
        COSCredentials credentials = new BasicCOSCredentials(storageBucket.getSecretId(),storageBucket.getSecretKey());
        ClientConfig clientConfig = new ClientConfig(new Region(storageBucket.getRegion()));
        COSClient cosClient = new COSClient(credentials,clientConfig);
        return cosClient;
    }

    @ApiOperation(value = "上传文件",notes = "系统文件服务接口")
    @PostMapping("/upload")
    public Result<SystemFile> upload(@RequestBody MultipartFile file){

        COSClient cosClient = cosClient();
        try {
            //1.获取文件名
            String fileName = file.getOriginalFilename();
            String newFileName = getRandomName(Objects.requireNonNull(fileName));
            //2.获取文件流对象
            InputStream inputStream = file.getInputStream();
            //3.客户端上传文件
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(inputStream.available());
            //四个参数：存储桶名称，文件名称，文件流对象，文件流长度
            cosClient.putObject(storageBucket.getBucketName(),newFileName, inputStream,objectMetadata);
            //4.返回云路径
            URL url = cosClient.generatePresignedUrl(storageBucket.getBucketName(),newFileName,null);

            SystemFile fileEntity = new SystemFile();
            fileEntity.setFileName(newFileName);
            fileEntity.setFilePath(storageBucket.getPath() + url.getPath());

            return Result.success(systemFileService.uploadFile(fileName,fileEntity));
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail(new SystemFile());
        } finally {
            //关闭 COSClient 对象
            cosClient.shutdown();
        }
    }

    @ApiOperation(value = "下载文件",notes = "系统文件服务接口")
    @PostMapping("/download")
    public Result<String> download(@RequestBody FileDeleteDto fileDeleteDto){
        /**
         * 腾讯云下载文件到本机指定文件夹
         */
        COSClient cosClient = cosClient();
        //本机的下载路径
        String downloadPath = System.getProperty("user.home") + "/Downloads/";

        List<Long> ids = fileDeleteDto.getIds();
        List<String> fileNames = fileDeleteDto.getFileNames();
        List<SystemFile> systemFiles = systemFileService.lambdaQuery().in(SystemFile::getId, ids).list();

        for (String fileName : fileNames) {
            SystemFile sysFile = systemFiles.stream().filter(systemFile -> systemFile.getFileName().equals(fileName)).collect(Collectors.toList()).get(0);
            File file = new File(downloadPath + sysFile.getRemark() + fileName.substring(fileName.lastIndexOf(".")));
            GetObjectRequest request = new GetObjectRequest(storageBucket.getBucketName(),fileName);
            cosClient.getObject(request, file);
        }
        // 关闭 COSClient 对象
        cosClient.shutdown();
        return Result.success("下载成功");
    }

    @ApiOperation(value = "删除文件",notes = "系统文件服务接口")
    @PostMapping("/deleteFile")
    public Result<Boolean> deleteFile(@RequestBody FileDeleteDto fileDeleteDto){
        COSClient cosClient = cosClient();
        List<Long> ids = fileDeleteDto.getIds();
        List<String> fileNames = fileDeleteDto.getFileNames();

        if (fileNames.size() == 1) {
            // 单个删除
            cosClient.deleteObject(storageBucket.getBucketName(),fileNames.get(0));

        } else {
            // 构造批量删除请求
            DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(storageBucket.getBucketName());
            // 设置要删除的对象键列表
            List<DeleteObjectsRequest.KeyVersion> keys = new ArrayList<>();
            for (String fileName : fileNames) {
                keys.add(new DeleteObjectsRequest.KeyVersion(fileName));
            }
            deleteObjectsRequest.setKeys(keys);
            // 执行批量删除请求
            cosClient.deleteObjects(deleteObjectsRequest);
        }

        // 关闭 COSClient 对象
        cosClient.shutdown();
        // 数据库删除文件，返回对象
        return Result.success(systemFileService.deleteFile(ids));
    }

    @ApiOperation(value = "分页查询文件",notes = "系统文件服务接口")
    @PostMapping("/pageFiles")
    public Result<Page<SystemFile>> pageFiles(@RequestBody FileDto fileDto){
        return Result.success(systemFileService.pageFiles(fileDto));
    }

    @ApiOperation(value = "更换头像",notes = "系统文件服务接口")
    @PostMapping("/updateIcon")
    public Result<Boolean> updateIcon(@RequestBody FileEntity fileEntity){
        return Result.success(systemFileService.updateIcon(fileEntity));
    }

    @ApiOperation(value = "默认头像",notes = "系统文件服务接口")
    @GetMapping("/defaultIcon")
    public Result<String> defaultIcon(){
        return Result.success(systemFileService.defaultIcon());
    }

    /**
     * 文件新名称
     * @param fileName
     * @return
     */
    public static String getRandomName(String fileName){
        int index=fileName.lastIndexOf(".");
        //获取文件格式
        String format=fileName.substring(index);
        return UUID.randomUUID().toString().replace("-","") + format;
    }
}
